package com.ganlucode.sipmock.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author GanLu
 * @date 2020-05-14 17:14
 */
@Slf4j
@Configuration
public class SipStackProperties extends Properties {

    @Value("${sip.sipstack-file-name}")
    private String filePath;
    @Autowired
    private Environment environment;

    /**
     * 读取配置并替换引用配置
     */
    @PostConstruct
    private void init(){
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties(filePath);
            for (String key : properties.stringPropertyNames()) {
                String value = properties.getProperty(key);
                String valueKey = getValueKey(value);
                if (StringUtils.isNotBlank(valueKey)) {
                    properties.put(key, environment.getProperty(valueKey));
                }
            }
            putAll(properties);
        } catch (IOException e) {
            log.error("配置文件初始化失败",e);
        }
    }


    public static String getValueKey(String text) {
        Pattern pattern = Pattern.compile("\\$\\{(.*)\\}");
        Matcher m = pattern.matcher(text);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }


}
